<?php
namespace addons\mall\controller;

use addons\mall\model\User;
use think\Db;
use think\Exception;
use think\Hook;

/**
 * 购物车控制器
 */
class Cart extends Base{
    protected $searchFields = 'id,title';
    protected $relationSearch = true;
    /**
     * Multi方法可批量修改的字段
     */
    protected $multiFields = 'checkis';

    public function _initialize() {
        parent::_initialize();
        $this->model = new \app\common\model\mall\goods\Cart;
    }

    /**
     * 加入购物车
     */
    public function getCartInfo()
    {
        $cart = $this->model->getCartInfo();
        return $this->request->isAjax() ? json($cart) : ($this->request->isPost() ? $this->success("",null,$cart) : $cart);
    }

    /**
     * 加入购物车
     */
    public function add(){
        $user_id = (int)cookie('uid');
        $goods_id = (int)input('post.goods_id');
        $goodsspec_id = (int)input('post.goodsspec_id');
        $cartNum = (int)input('post.num',1);
        $cartNum = ($cartNum>0)?$cartNum:1;
        $type = (int)input('post.type');
        //验证传过来的商品是否合法
        $chk = $this->checkGoodsSaleSpec($goods_id,$goodsspec_id);
        $goodsspec_id = $chk['salespec_id'];
        //用户购买实物
        if($user_id > 0 ) {
            //实物产品库存检测
            if (!$chk['goodstype']) {
                if ($chk['stock'] < $cartNum) $this->error("加入购物车失败，商品库存不足");
            }
            $goods = $this->model->where(['user_id' => $user_id, 'goods_id' => $goods_id, 'salespec_id' => $goodsspec_id])->select();

            try {
                if (count($goods) == 0) {
                    $data = array();
                    $data['user_id'] = $user_id;
                    $data['goods_id'] = $goods_id;
                    $data['salespec_id'] = $goodsspec_id;
                    $data['checkis'] = 1;
                    $data['num'] = $cartNum;
                    $rs = $this->model->allowField(true)->save($data);
                } else {
                    $rs = $this->model->where(['user_id' => $user_id, 'goods_id' => $goods_id, 'salespec_id' => $goodsspec_id])->setInc('num', $cartNum);
                }
                if (false !== $rs) {
                    if ($type == 1) {
                        $cartId = $this->model->where(['user_id' => $user_id, 'goods_id' => $goods_id, 'salespec_id' => $goodsspec_id])->value('id');
                        $this->model->where("id = " . $cartId . " and user_id=" . $user_id)->setField('checkis', 1);
                        $this->model->where("id != " . $cartId . " and user_id=" . $user_id)->setField('checkis', 0);
                        $this->model->where(['id' => $cartId, 'user_id' => $user_id])->setField('num', $cartNum);
                    }

                    if (!$chk['goodstype']) {
                        $this->success("添加成功",null,$this->model->getCartInfo());
                    } else {//如果是虚拟产品则自动进入购买流程
                        $this->success("添加成功", null, ['forward' => 'index']);
                    }
                }
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        else{
            //游客购物或购买虚拟产品
            $carts = [];
            $carts['goods_id'] = $goods_id;
            $carts['num'] = $cartNum;
            $carts['salespec_id'] = $goodsspec_id;
            $carts['goodstype'] = $chk['goodstype'];
            session('TMP_CARTS',$carts);
            $this->success("添加成功",null,['forward'=>'indexVisitor']);
        }
        $this->error("加入购物车失败");
    }

    /**
     * 查看购物车列表
     */
    public function index()
    {
        $ids = input('ids');
        if ($this->request->isAjax()) {

            $list = $this->model->getCartList($ids);

            return json($list);
        }
        return $this->view->fetch();
    }

    /**
     * 游客下单
     */
    public function indexVisitor(){
        $num = $this->request->param("num");
        if ($this->request->isAjax()) {
            $list = $this->model->getVisitorCart($num);
            $this->success("",null,$list);
        }
        return $this->view->fetch();
    }

    /**
     * 更新购物车商品数量
     */
    public function update($ids = "")
    {
        $ids = $ids ? $ids : $this->request->param("ids");
        $num = intval(input('get.num'));
        if ($ids) {
            Db::startTrans();
            try {
                $this->model->allowField(true)->isUpdate(true)->save(["num"=>$num],["id"=>['in', $ids]]);
                Db::commit();
                $this->success();

            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->error(__('No rows were updated'));

        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 更新购物车选择
     */
    public function multi($ids = "")
    {
        $ids = $ids ? $ids : $this->request->param("ids");
        $checkis = $this->request->param("checkis/d");
        Db::startTrans();
        try {
            if ($ids) {
                $this->model->allowField(true)->isUpdate(true)->save(["checkis" => $checkis], ["id" => ['in', $ids]]);
            }
            Db::commit();
            $this->success();

        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->error(__('No rows were updated'));

    }
    /**
     * 删除购物车里的商品
     */
    public function del(){
        $user_id = (int)cookie('uid');
        $id = input('get.ids');
        $id = explode(',',$id);
        $id = array_filter($id);
        $this->model->where(['user_id'=>$user_id,'id'=>['in', $id]])->delete();
        $this->success("删除成功");
    }

    /**
     * 验证商品规格
     */
    public function checkGoodsSaleSpec($goods_id,$goodsspec_id){
        $goods = \app\common\model\mall\goods\Goods
            ::where(['id'=>$goods_id,'status'=>['in',['sale','warn']],'goodsstatus'=>1])
            ->field('id,specis,goodsstock,goodstype')->find();
        if(empty($goods))$this->error("添加失败，无效的商品信息");
        $goodsStock = (int)$goods['goodsstock'];
        //有规格的话查询规格是否正确
        if($goods['specis']==1){
            $specs = db('mall_goods_salespec')
                ->where('goods_id',$goods_id)
                ->field('id,defaultis,specstock')->select();
            if(count($specs)==0){
                $this->error("添加失败，无效的商品信息");
            }
            $defaultgoodsspec_id = 0;
            $defaultGoodsSpecStock = 0;
            $isFindSpecId = false;
            foreach ($specs as $key => $v){
                if($v['defaultis']==1){
                    $defaultgoodsspec_id = $v['id'];
                    $defaultGoodsSpecStock = (int)$v['specstock'];
                }
                if($v['id']==$goodsspec_id){
                    $goodsStock = (int)$v['specstock'];
                    $isFindSpecId = true;
                }
            }
            //有规格却找不到规格的话就报错
            if($defaultgoodsspec_id==0) $this->error("添加失败，无效的商品规格");
            //如果没有找到的话就取默认的规格
            if(!$isFindSpecId) return ['salespec_id'=>$defaultgoodsspec_id,
                'stock'=>$defaultGoodsSpecStock,
                'goodstype'=>$goods['goodstype']];
            return ['salespec_id'=>$goodsspec_id,
                'stock'=>$goodsStock,
                'goodstype'=>$goods['goodstype']];
        }else{
            return ['salespec_id'=>0,
                'stock'=>$goodsStock,
                'goodstype'=>$goods['goodstype']];
        }
    }

}
